circle = [1, 6, 7, 2, 4, 8, 3, 5, 9]

# next_cup[c] = nc => nc after c
next_cup = [0] * (len(circle) + 1)

for (pre, next) in zip(circle, circle[1:] + [circle[0]]):
    next_cup[pre] = next

curr = circle[0]
mod = max(circle)


for _ in range(100):
    # get next 3 cup
    next1 = next_cup[curr]
    next2 = next_cup[next1]
    next3 = next_cup[next2]

    # get destination cup
    dest = (curr - 2) % mod + 1
    while dest in (next1, next2, next3):
        dest = (dest - 2) % mod + 1

    # move 'next 3' after destination 
    # move after_next3 after curr

    after_dest = next_cup[dest]
    after_next3 = next_cup[next3]

    next_cup[dest] = next1
    next_cup[curr] = after_next3
    next_cup[next3] = after_dest

    curr = next_cup[curr]

iter = next_cup[1]
result = ''
while iter != 1:
    result += str(iter)
    iter = next_cup[iter]

print(result)

